from max30102 import *
from machine import sleep, SoftI2C, Pin, ADC, UART, PWM
from conf import featherGuard as conf
import time
import asyncio

#============System Init=============
i2c = SoftI2C(sda=Pin(conf.PPG_SDA), scl=Pin(conf.PPG_SCL), freq=conf.PPG_I2C_FREQ)
ppgsensor = MAX30102(i2c=i2c)
if ppgsensor.i2c_address not in i2c.scan():
    print("[* SWE] (error) 未能发现ppg传感器于: (sclk:", conf.PPG_SCL, "sda: ", conf.PPG_SDA, ")")
elif not (ppgsensor.check_part_id()):
    print("[* SWE] (error) 传感器型号不对 ，请检查位于(sclk:", conf.PPG_SCL, "sda: ", conf.PPG_SDA, ")的传感器是否为max30102或max30105")
else:
    print("[* SWE] (info) 恭喜！传感器正常连接。")
ppgsensor.setup_sensor()#PPGINIT

sensorsdn = Pin(conf.ECG_SDN, Pin.OUT)#ECGenable
sensorsdn.on()
ecgsensor = ADC(Pin(conf.ECG_ADC))
ecgsensor.atten(ADC.ATTN_11DB)
ecgsensor.width(ADC.WIDTH_12BIT)#ECGINIT

machineAbove = UART(conf.UART_ID, baudrate = conf.UART_BAUD, timeout = conf.UART_TIMEOUT_LIMIT)#UART_UPLOAD_INIT
#actual_acquisition_rate = int(sensor_sample_rate / sensor_fifo_average)
#=======================================

#===============Functional Functions Area=======================
def siren_sound(pin=conf.BUZZER, min_freq=500, max_freq=2000, step=50, sweep_speed=10, duration=conf.BUZZ_DURATION):
    buzzer = PWM(Pin(pin), duty_u16=0)  # 初始化PWM，初始占空比0（静音）
    end_time = time.ticks_add(time.ticks_ms(), duration * 1000)  # 计算结束时间
    
    try:
        while time.ticks_diff(end_time, time.ticks_ms()) > 0:
            # 频率上升（min_freq → max_freq）
            for freq in range(min_freq, max_freq, step):
                buzzer.freq(freq)
                buzzer.duty_u16(32768)  # 50%占空比（0-65535范围）
                time.sleep_ms(sweep_speed)
            
            # 频率下降（max_freq → min_freq）
            for freq in range(max_freq, min_freq, -step):
                buzzer.freq(freq)
                buzzer.duty_u16(32768)
                time.sleep_ms(sweep_speed)
    finally:
        buzzer.duty_u16(0)  # 结束后强制静音
        buzzer.deinit()      # 释放PWM资源
        
def detectECGexception():
    lo_plus = Pin(conf.LO_PLUS, mode = Pin.IN, pull = Pin.PULL_UP)
    lo_minus = Pin(conf.LO_MINUS, mode = Pin.IN, pull = Pin.PULL_UP)
    if lo_plus.value() == 1:
        if lo_minus.value() == 1:
            return [conf.BOTH_ARM_FALLOFF, "双臂电极掉落！"]
        else:
            return [conf.LEFT_ARM_FALLOFF, "左臂电极掉落！"]
    else:
        if lo_minus.value() == 1:
            return [conf.RIGHT_ARM_FALLOFF, "右臂电极掉落！"]
        return [conf.NORMAL, "正常"]
    
def packdata(red: int, ir: int, ecg: int, green: int, time: int):
    fmt = "iiiii"
    data = [red, ir, ecg, green, time]
    return struct.pack(fmt, *data)
#=============================================================



global red
global green
global ir
global ecg
red : int = 0
green : int = 1
ir : int = 0
ecg : int = 0#Variables INIT

#原始数据输出
#time.sleep(5)
print("[* SWE]")
while True:
    time.sleep_ms(80)
    ppgsensor.check()
    red = ppgsensor.pop_red_from_storage()
    green = ppgsensor.pop_green_from_storage()
    ir = ppgsensor.pop_ir_from_storage()
    ecg = ecgsensor.read()
#    print("red",red,"ir",ir,"green",green,"ecg",ecg)
    print(ecg)
